import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../names.dart';
import '../../services/storage_service.dart';

/// 认证中间件 - 检查用户登录状态
class AuthMiddleware extends GetMiddleware {
  @override
  int? get priority => 1;

  @override
  RouteSettings? redirect(String? route) {
    // 获取存储服务
    final storageService = Get.find<StorageService>();
    
    // 检查用户是否已登录
    if (!storageService.isLoggedIn) {
      debugPrint('🔒 用户未登录，重定向到登录页面');
      debugPrint('🔗 原始路由: $route');
      
      // 保存原始路由，登录成功后可以返回
      if (route != null && route != RouteNames.systemLogin) {
        storageService.setString('redirect_route', route);
      }
      
      // 重定向到登录页面
      return const RouteSettings(name: RouteNames.systemLogin);
    }
    
    debugPrint('✅ 用户已登录，允许访问: $route');
    return null;
  }

  @override
  GetPage? onPageCalled(GetPage? page) {
    debugPrint('🔍 认证中间件检查页面: ${page?.name}');
    return super.onPageCalled(page);
  }

  @override
  List<Bindings>? onBindingsStart(List<Bindings>? bindings) {
    debugPrint('🔗 认证中间件绑定开始');
    return super.onBindingsStart(bindings);
  }

  @override
  GetPageBuilder? onPageBuildStart(GetPageBuilder? page) {
    debugPrint('🏗️ 认证中间件页面构建开始');
    return super.onPageBuildStart(page);
  }
}

/// 登录后重定向帮助类
class AuthRedirectHelper {
  /// 登录成功后重定向到原始页面
  static void redirectAfterLogin() {
    final storageService = Get.find<StorageService>();
    final redirectRoute = storageService.getString('redirect_route');
    
    if (redirectRoute != null && redirectRoute.isNotEmpty) {
      debugPrint('🔄 登录成功，重定向到原始页面: $redirectRoute');
      storageService.remove('redirect_route');
      Get.offAllNamed(redirectRoute);
    } else {
      debugPrint('🏠 登录成功，跳转到主页面');
      Get.offAllNamed(RouteNames.systemMain);
    }
  }

  /// 清除重定向路由
  static void clearRedirectRoute() {
    final storageService = Get.find<StorageService>();
    storageService.remove('redirect_route');
  }
}
